#include "worldtcpsrtproc.h"
#include "ctaskproc.h"
#include "custombox.h"
#include "funcmgr.h"

WorldTcpSerProc::WorldTcpSerProc()
{
    WorldTcpServer = new QTcpServer();

    ForwardIp = QSNULL;
    ForwardPort = 0;
    IsSerStart = false;
}

WorldTcpSerProc::~WorldTcpSerProc()
{
    delete WorldTcpServer;
}

//启动转发监听服务
bool WorldTcpSerProc::DoStart(QString ChoiceIp, quint16 LocalPort, quint16 FdPort)
{
    if (IsSerStart)
        return true;

    //监听本地端口 等待连接
    if (!WorldTcpServer->listen(QHostAddress::AnyIPv4, LocalPort))
    {
        IsSerStart = false;
        WorldTcpServer->close();
        return false;
    }

    ForwardIp = ChoiceIp;
    ForwardPort = FdPort;

    QObject::connect(WorldTcpServer, SIGNAL(newConnection()), this, SLOT(AcceptConnect()));
    IsSerStart = true;
    return true;
}

void WorldTcpSerProc::DoStop()
{
    if (IsSerStart)
    {
        IsSerStart = false;
        WorldTcpServer->close();

        //如果不关闭 玩家在被封禁后依然可以进行游戏
        foreach(QTcpSocket *Client, ConnectClients)
            Client->close();
    }
}

void WorldTcpSerProc::AcceptConnect()
{
    if (!WorldTcpServer)
        return;

    //从监听端口得到Socket
    QTcpSocket*  TcpSocket = WorldTcpServer->nextPendingConnection();

    ConnectClients.append(TcpSocket);

    QObject::connect(TcpSocket, SIGNAL(disconnected()), this, SLOT(RemoveProcClient()));

    QString Count = sFunc->GetConfigValue(MaxCon);
    if (ConnectClients.length() > Count.toInt())
    {
        TcpSocket->close();
        sFunc->MBoxShow(QStringLiteral("游戏配置最多只能 [ %1 ]  连接\n\n请遵守游戏规则").arg(Count));
        return;
    }

    //初始化执行转发过程
    CtaskProc* TaskProc = new CtaskProc(TcpSocket, ForwardIp, ForwardPort);
    TaskProc->StartForwardProc();
}

void WorldTcpSerProc::RemoveProcClient()
{
    QTcpSocket *ProcClient = qobject_cast<QTcpSocket*>(sender());
    ConnectClients.removeOne(ProcClient);
}
